<?php
namespace app\api\service;
use think\Controller;
use think\Db;

class Order extends Controller {
    static protected $err_code = 0;
    // 生成服务需求单
    static public function order_server($param) {
        if( !isset($param['member_id']) || !isset($param['type']) || !isset($param['msg'])
            || !isset($param['service_time']) || !isset($param['phone'])
            || !isset($param['service_mode']) || !isset($param['address']) || !isset($param['source']) || !isset($param['lat'])|| !isset($param['lon'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try{

            if(isset($param['repair_id']) && $param['repair_id']){
                $where = ' id='.intval($param['repair_id']).' AND audit_status = 4 ';
                $repair = Db::table('mob_repair')->field('repair_name')->where($where)->find();
                if(!$repair){
                    self::$err_code = 400136;
                    throw new \Exception('FAULT');
                }
            }

            //组装数据
            $order_sn = date("YmdHis") . rand(10000, 99999);
            $data['order_sn'] = $order_sn; //订单号
            $data['member_id'] = $param['member_id']; // 用户ID
            $data['type'] = $param['type']; //需求类型 1、图片  2、拖车  3、维修  4、保养
            $data['add_time'] = time();  // 申请时间
            $data['push_time'] = time();  // 下单成功立即推送
            $data['status'] = 1;  // 下单成功
            $data['msg'] = $param['msg'];  // 需求描述
            $data['service_time'] = $param['service_time'];  // 服务时间
            $data['phone'] = $param['phone']; // 联系电话
            $data['service_mode'] = $param['service_mode']; // 处理方式 1、上门；  2、到店
//            $data['province'] = get_region($param['province']); // 省
//            $data['city'] = get_region($param['city']); // 市
//            $data['area'] = get_region($param['area']); // 区
//            $data['street'] = get_region($param['street']); // 街道
            $data['address'] = $param['address']; // 详细地址
            $data['lat'] = $param['lat']; // 纬度
            $data['lon'] = $param['lon']; // 经度

            $data['source'] = $param['source']; // 订单来源

            if (isset($param['img1']) || isset($param['img2']) || isset($param['img3']) || isset($param['img4']) || isset($param['img5'])) {
                if (isset($param['img1'])) $data['img1'] = $param['img1']; // 图1
                if (isset($param['img2'])) $data['img2'] = $param['img2']; // 图2
                if (isset($param['img3'])) $data['img3'] = $param['img3']; // 图3
                if (isset($param['img4'])) $data['img4'] = $param['img4']; // 图4
                if (isset($param['img5'])) $data['img5'] = $param['img5']; // 图5
            } else {
                self::$err_code = 400135;
                throw new \Exception('FAULT');
            }

            //print_r($data);exit();

            if(isset($param['repair_id']) && $param['repair_id']){
                $data['repair_id'] = $param['repair_id']; // 维修店ID
                $data['status'] = 11;  // 议价中
                $data['order_receiving_time'] = time();  // 接单时间
                $data['overtime'] = time() + 600;  // 议价结束时间  10分钟
            }

            $order_id = Db::table('mob_order_server')->insertGetId($data);

            if(isset($param['repair_id']) && $param['repair_id']){
                $where = ' r.id = '.$param['repair_id'].' AND r.audit_status = 4 ';
            }else{
                // 根据下单用户经纬度 获取维修店列表
                $coord = getAround($param['lat'], $param['lon'], 3000);
                $where = ' r.audit_status = 4 AND r.lat > ' . $coord[0] . ' AND r.lat < ' . $coord[1] . ' AND r.lon > ' . $coord[2] . ' AND r.lon < ' . $coord[3] . ' ';
            }
            $repair_list = Db::table('mob_repair')->alias('r')
                ->field('r.member_id, m.phone m_phone, m.openid')
                ->join('mob_member m', 'r.member_id = m.id')
                ->join('mob_repair_maintenance_server_item rsi', 'rsi.repair_id = r.id AND rsi.maintenance_item_id = ' . $data['type'])
                ->where($where)->select();
            //file_put_contents('repair.txt', json_encode($repair_list));
            foreach ($repair_list as $v) {
                // 检查维修店的是否存在与订单相符的主营项目
                $params = [
                    'order_id' => $order_id,
                    'member_id' => $v['member_id'],
                    'order_sn' => $order_sn,
                    'm_phone' => $v['m_phone'],
                    'openid' => $v['openid'],
                ];
                //file_put_contents('repair.txt', json_encode($params) . " \n \n ", FILE_APPEND);
                new_order_push_msg($params); // 新订单消息推送
            }

//            // 调用极光推送接口
//            $JPush_api = new JPushApi();
//            $JPush_api->index('附近有新订单', $data['longitude'], $data['latitude']);

            Db::commit();
            return ['data'=>['server_demand_id' => $order_id], 'code'=>200, 'msg'=> 'SUCCESS'];

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }

    // 维修店抢单接口
    static public function order_server_receiving($param) {
        if(!isset($param['order_id']) || !isset($param['repair_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        // 启动事务
        Db::startTrans();
        try{
            // 检查订单状态
            $order = Db::name('order_server')->alias('o')
                ->field('o.status,o.order_sn, o.id, o.member_id, m.phone, m.openid')
                ->join('mob_member m', 'o.member_id = m.id')
                ->where('o.id', $param['order_id'])->find();
            if ( $order["status"] != 1 ) {
                self::$err_code = 400089;
                throw new \Exception('FAULT');
            }


            $repair_id = $param['repair_id'];
            $order_id = $param['order_id'];
            //检查是否允许抢单
            $check_count = Db::table('mob_order_receiving_log')->where('repair_id', $repair_id)->where('order_id', $order_id)->count();
            if($check_count >= 2) {
                self::$err_code = 400048;
                throw new \Exception('FAULT');
            }
            // 组装订单数据
            $data['status'] = 11; // 抢单议价状态
            $data['repair_id'] = $param['repair_id']; // 维修店ID
            $data['order_receiving_time'] = time();  // 接单时间
            $data['overtime'] = time() + 600;  // 议价结束时间  10分钟
            $order_id = Db::name('order_server')->where('id', $param['order_id'])->update($data);
            // 添加接单记录
            Db::table('mob_order_receiving_log')->insert(['repair_id' => $param['repair_id'], 'order_id' => $param['order_id'], 'add_time' => time()]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

        // 调用极光推送接口
//        $JPush_api = new JPushApi();
//        $JPush_api->index('谁谁谁已经接受您的服务需求订单，请及时联系沟通具体需求！');

        $url = 'http://'.$_SERVER["HTTP_HOST"].'/wechat/orders/order_info.html?id=' . $order["id"];

        //$order["id"] $order["phone"] $order["openid"]
        /*发送短信*/
        if (isset($order["phone"]) && $order["phone"]) {
            $param = [
                'phone' => $order["phone"],
                'type' => 31,
                'model' => 3053108
            ];
            \app\api\service\Common::send_note($param);
        }

        // 发送微信模板消息
        if (isset($order["openid"]) && $order["openid"]) {
            $data = [
                'touser' => $order["openid"],
                'template_id' => 'rnJUnlEzUqYEEwmXLKm-U2LpMW90D-7l71DqIzp4tkY',
                'url' => $url,
                'topcolor' => '#FF0000',
                'data' => [
                    'first' => [
                        'value' => '维修店接单提醒',
                        "color" => "#173177"
                    ],
                    'keyword1' => [
                        'value' => '订单被接单',
                        "color" => "#173177"
                    ],
                    'keyword2' => [
                        'value' => date('Y-m-d H:i:s'),
                        "color" => "#173177"
                    ],
                    'remark' => [
                        'value' => '您的订单被接单,请等待维修店推送服务给您.',
                        "color" => "#173177"
                    ]
                ]
            ];
            send_msg($data);
        }

        /*****
         * 推送站内信息 *  ****/
        $param1 = [
            'member_id' => $order['member_id'],
            'member_role' => 'member',
            'msg_id' => 52,
        ];
        $param2 = [
            $order['order_sn'], date('Y-m-d H:i:s'), 'url' => $url
        ];
        \app\api\service\Message::creation_order_msg($param1, $param2);



        return ['data'=>['order_server_id' => $order_id], 'code'=>200, 'msg'=> 'SUCCESS'];
    }

    // 维修店抢单之后回复接口
    static public function order_server_receiving_replytime($param) {
        if(!isset($param['order_id']) || !isset($param['repair_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            // 组装订单数据
            $data['replytime'] = time();  // 接单时间
            $order_id = Db::table('mob_order_server')->where('id', $param['order_id'])->where('repair_id', $param['repair_id'])->update($data);
            return ['data'=>['order_server_id' => $order_id], 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 维修店与用户沟通完毕生成正式订单接口
    static public function order_server_create($param) {
        if(!isset($param['order_id']) || !isset($param['repair_id']) || !isset($param['price']) || !isset($param['products']) || !is_array($param['products']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        // 获取订单数据
        $order = Db::table('mob_order_server')->where('id', $param['order_id'])->where('repair_id', $param['repair_id'])->find();
        if(!$order) return ['data'=>'','code'=>400056,'msg'=> 'FAULT']; // 订单不存在
        if($order['status'] != 1) return ['data'=>'','code'=>400057,'msg'=> 'FAULT']; // 订单状态异常

        // 启动事务
        Db::startTrans();
        try{

            // 组装订单数据
            $data['order_price'] = $param['price']; // 订单价格
            $data['status'] = 2;  // 订单状态   待付款
            if(!isset($param['replymsg'])) $data['replymsg'] = $param['replymsg'];  // 维修店备注内容
            Db::table('mob_order_server')->where('id', $param['order_id'])->where('repair_id', $param['repair_id'])->update($data);

            //订单产品
            $products = $param['products'];
            foreach($products as $v => $p) {
                if($p['type'] == 3 && (!isset($p['msg']) || empty($p['msg']))) {
                    self::$err_code = 400082;
                    throw new \Exception('FAULT');
                }
                $products[$v]['order_id'] = $param['order_id'];
            }
            Db::table('mob_order_product_server')->insertAll($products);
            // 提交事务
            Db::commit();

            // 调用极光推送接口
            $JPush_api = new JPushApi();
            $JPush_api->index('订单信息以完善，请尽快付款');

            return ['code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 创建购买订单接口
    static public function order_buy_create($param) {
        if(!isset($param['member_id']) || !isset($param['consignee']) || !isset($param['phone']) || !isset($param['province']) ||
            !isset($param['city']) || !isset($param['area']) || !isset($param['street']) || !isset($param['address']) ||
            !isset($param['postcode']) || !isset($param['cart_ids']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        // 分析购物车产品   来自不同店铺的话  需要分单
        $products = Db::table('mob_cart')->alias('c')
            ->field('c.*, sp.shop_id, sp.price')
            ->join('mob_shop_product as sp', 'sp.id = c.product_id')
            ->where('c.id', 'in', $param['cart_ids'])
            ->select();
        $shop_products = [];
        if(empty($shop_products)) {
            self::$err_code = 400062;
            throw new \Exception('FAULT');
        }
        foreach ($products as $v) {  //循环产品  按店铺ID分组
            $shop_products[$v['shop_id']][] = $v;
        }

        // 启动事务
        Db::startTrans();
        try{
            $count_order = count($shop_products);
            $main_order_sn = $count_order > 0 ? date("YmdHis") . rand(10000, 99999) : ''; // 如果需要分单 创建主订单的订单号
            $total_product_price = $total_freight = 0; // 初始化总的订单价格和运费价格  如果需要分单  支付时使用

            // 根据分组好的产品创建订单
            foreach ($shop_products as $shop_id => $goods) {
                // 计算产品价格
                $product_price = 0;
                foreach ($goods as $g) {
                    $product_price += $g['price'] * $g['product_num'];
                }
                // 运费 计算方式待定
                $freight = 0;
                //订单数据
                $order_data = [
                    'member_id' => $param['member_id'], //用户ID
                    'order_sn' => date("YmdHis") . rand(10000, 99999), //订单号
                    'shop_id' => $shop_id, //店铺ID
                    'product_price' => $product_price, //订单产品价格
                    'freight' => $freight, // 运费
                    'consignee' => $param['consignee'], //收货人
                    'phone' => $param['phone'], //收获人手机号码
                    'province' => $param['province'], //省
                    'city' => $param['city'], //市
                    'area' => $param['area'], //区
                    'street' => $param['street'], //街道地址
                    'address' => $param['address'], //详细地址
                    'postcode' => $param['postcode'], //邮政编码
                    'status' => 1, //订单状态
                    'add_time' => time(), //下单时间
                    'main_order_sn' => $main_order_sn // 主订单 订单号
                ];
                $order_id = Db::table('mob_order_buy')->insertGetId($order_data);

                //组装订单产品数据
                $order_product = [];
                foreach ($goods as $g) {
                    $order_product[] = [
                        'order_id' => $order_id,
                        'product_id' => $g['product_id'],
                        'product_name' => $g['product_name'],
                        'product_num' => $g['product_num'],
                        'product_price' => $g['price'],
                        'product_attr_id' => 0,
                        'product_image' => $g['product_img']
                    ];
                }
                Db::table('mob_order_product_buy')->insertAll($order_product);
            }

            // 如果是多个店铺的产品 表示需要分单  创建主订单  用于支付
            if(count($shop_products) > 1) {
                //订单数据
                $order_data = [
                    'member_id' => $param['member_id'], //用户ID
                    'order_sn' => $main_order_sn, //订单号
                    'product_price' => $total_product_price, //订单产品价格
                    'freight' => $total_freight, // 运费
                    'status' => 1, //订单状态
                    'add_time' => time(), //下单时间
                    'is_main_order' => 1
                ];
                $order_id = Db::table('mob_order_buy')->insertGetId($order_data);
            }
            // 提交事务
            Db::commit();
            return ['data'=>['order_id' => $order_id], 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 订单支付接口
    static public function order_pay($param) {
        if(!isset($param['order_id']) || !isset($param['member_id']) || !isset($param['model']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        if($param['model'] != 'order_buy' && $param['model'] != 'order_server') return ['data'=>'','code'=>400061,'msg'=> 'FAULT']; // 订单模型错误

        try{
            $model = $param['model'];
            if ($model == 'order_server') {
                $join = [ ['mob_repair r','r.id = o.repair_id', 'LEFT'] ];
                $field = 'o.*, r.repair_name as company_name, r.cover';
            } else {
                $join = [ ['mob_shop s','r.s = o.shop_id', 'LEFT'] ];
                $field = 'o.*, s.shop_name as company_name, s.cover';
            }
            $order = Db::table('mob_'.$model)->alias('o')->field($field)->join($join)
                ->where('o.id', $param['order_id'])
                ->where('o.member_id', $param['member_id'])
                ->find();
            if (!($model == 'order_buy' && $order['status'] == 1) && !($model == 'order_server' && $order['status'] == 2)) {
                self::$err_code = 400057;
                throw new \Exception('FAULT');
            }
            return ['data'=>$order,'code'=>200,'msg'=> 'SUCCESS']; // 返回支付订单数据
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 服务订单状态更改接口
    static public function update_order_server_status($param) {
        if(!isset($param['order_id']) || !isset($param['member_id']) || !isset($param['status']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        if($param['status'] != 6 && $param['status'] != 9) return ['data'=>'','code'=>400058,'msg'=> 'FAULT']; // 提交订单状态错误
        
        // 启动事务
        Db::startTrans();
        try{

            if($param['model']=="order_server_deal"){
                $order = Db::table('mob_order_server_deal')->field('status, order_sn, repair_id, order_price, member_id_to as member_id, coupon_id')->where('id', $param['order_id'])->where('member_id_to', $param['member_id'])->find();
            }else{
                $order = Db::table('mob_order_server')->field('status, order_sn, repair_id, order_price, member_id, coupon_id')->where('id', $param['order_id'])->where('member_id', $param['member_id'])->find();
            }
            
            if(!$order) {
                self::$err_code = 400056;
                throw new \Exception('FAULT');
            }

            if ($param['status'] == 6 && ($order['status'] != 3  && $order['status'] != 4)) {  // 只有待收货和工作完成状态的可以确认完成
                self::$err_code = 400057;
                throw new \Exception('FAULT');
            }

            if ($param['status'] == 9 && $order['status'] != 1) { // 只有未支付的可以取消
                self::$err_code = 400057;
                throw new \Exception('FAULT');
            }
            switch ($param['status']) {
                case 6:
                    $update_data = [
                        'status' => 6,
                        'finish_time' => time()
                    ];
                    // 用户确认完成，将维修店对应的冻结金额转入可用余额
                    if($param['model']=="order_server_deal"){
                        $where['order_model'] = 'order_server_deal';
                    }else{
                        $where['order_model'] = 'order_server';
                    }
                    $where['order_sn'] = $order['order_sn'];
                    //$bill = Db::table('mob_member_money')->where($where)->order('id desc')->find(); // 获取账单记录
                    $settlement_amount = $order['order_price']; // 结算金额以订单金额为准
                    $poundage = $settlement_amount * config('system.settlement_proportion');  // 扣除  手续费
                    // 检查是否有优惠券
                    if(isset($order['coupon_id']) && $order['coupon_id'] > 0) {
                        $coupon = Db::table('mob_member_coupon')->alias('mc')->field('c.money, c.coupon_type')
                            ->join('mob_coupon c', 'c.id = mc.coupon_id')->where('mc.id', $order['coupon_id'])->find();
                        if ($coupon['coupon_type'] == 2) {
                            $settlement_amount -= $coupon['money'];
                        }
                    }
                    $settlement_amount -= $poundage;
                    Db::table('mob_repair')->where('id', $order['repair_id'])->update([
                        'money'  => ['exp','money+' . $settlement_amount],  // 转入金额 为订单金额 - 商家优惠券金额 - 手续费
                        'money_frozen' => ['exp','money_frozen-' . $order['order_price']],  // 减去订单金额对应的冻结金额
                    ]);

                    $repair_member_id = Db::table('mob_repair')->where('id', $order['repair_id'])->value('member_id');

                    $member_money = [
                        [
                            'member_id' => $repair_member_id, // 维修店用户ID
                            'money' => $poundage,  // 账单金额
                            'frozen_status' => 1, // 冻结状态，， 此处冻结，等订单彻底完成时，自动将冻结金额转为可用余额
                            'type' => 1, // 用户账户类型  1、普通账户  2、维修店账户  3、供应商账户  4、合伙人账户
                            'msg' => '扣除订单手续费', // 账单说明
                            'source' => 14, // 资金来源 0、出账； 1、业务进账； 2、普通账户转入； 3、维修店转入； 4、经销商转入； 5、合伙人转入;  6 提现； 7 分销
                            'add_time' => time(), // 账单生成时间，
                            'order_sn' => $order['order_sn'], // 订单号
                            'order_model' => 'order_server', // 订单模型
                            'pay_type' => '订单手续费' // 交易方式
                        ],
                        [
                            'member_id' => $repair_member_id, // 维修店用户ID
                            'money' => $settlement_amount,  // 账单金额
                            'frozen_status' => 1, // 冻结状态，， 此处冻结，等订单彻底完成时，自动将冻结金额转为可用余额
                            'type' => 1, // 用户账户类型  1、普通账户  2、维修店账户  3、供应商账户  4、合伙人账户
                            'msg' => '订单收入', // 账单说明
                            'source' => 1, // 资金来源 0、出账； 1、业务进账； 2、普通账户转入； 3、维修店转入； 4、经销商转入； 5、合伙人转入;  6 提现； 7 分销
                            'add_time' => time(), // 账单生成时间，
                            'order_sn' => $order['order_sn'], // 订单号
                            'order_model' => 'order_server', // 订单模型
                            'pay_type' => '订单收入' // 交易方式
                        ]
                    ];
                    Db::table('mob_member_money')->insertAll($member_money); // 增加账单

                    // 如果订单用户存在上级，则上级用户分成
                    // 获取订单用户上级ID
                    if($param['model']!="order_server_deal"){
                        $parents = db('member')->where('id', $order['member_id'])->value('parents');
                        if ($parents) {
                            $parents = explode(',', $parents);
                            rsort($parents);
                            $i = 0;
                            foreach ($parents as $parent_id) {
                                if ($i > 1) {
                                    break;  // 超过两级  跳出循环
                                }
                                if ($i == 0) {  // 根据不同级别获取不同的分销比例
                                    $distribution_proportion = config('system.one_level_proportion');
                                } else {
                                    $distribution_proportion = config('system.two_level_proportion');
                                }
                                if ($parent_id > 0) {   // 分销收益=手续费*分销比例
                                    $rebate = $poundage * $distribution_proportion;
                                    Db::table('mob_member')
                                        ->where('id', $parent_id)
                                        ->setInc('distribution_money', $rebate); // 分销收益金额
                                    $member_money = [
                                        'member_id' => $parent_id, // 用户ID  此处是为订单用户的上级生成账单
                                        'money' => $rebate,  // 账单金额
                                        'frozen_status' => 1, // 冻结状态，， 此处冻结，等订单彻底完成时，自动将冻结金额转为可用余额
                                        'type' => 1, // 用户账户类型  1、普通账户  2、维修店账户  3、供应商账户  4、合伙人账户
                                        'msg' => '分销收益', // 账单说明
                                        'source' => 7, // 资金来源 0、出账； 1、业务进账； 2、普通账户转入； 3、维修店转入； 4、经销商转入； 5、合伙人转入;  6 提现； 7 分销
                                        'add_time' => time(), // 账单生成时间，
                                        'order_sn' => $order['order_sn'], // 订单号
                                        'order_model' => 'order_server', // 订单模型
                                        'pay_type' => '订单返利' // 交易方式
                                    ];
                                    Db::table('mob_member_money')->insert($member_money); // 增加账单
                                    $i++;
                                }
                            }
                        }
                    }

                    //----------------------------------------
                    break;
                case 9:
                    $update_data = [
                        'status' => 9,
                        'cancel_time' => time()
                    ];
                    break;
            }

            if($param['model']=="order_server_deal") {
                Db::table('mob_order_server_deal')->where('id', $param['order_id'])->where('member_id_to', $param['member_id'])->update($update_data);
            }else{
                Db::table('mob_order_server')->where('id', $param['order_id'])->where('member_id', $param['member_id'])->update($update_data);
            }
            Db::commit();
            return ['data'=>'', 'code'=>200, 'msg'=> 'SUCCESS'];

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取服务单产品列表
    static public function server_order_goods($param) {
        if (!isset($param['order_id']))
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        try{
            $order = db('order_server')->alias('o')->field('o.order_sn, o.order_price, o.status, o.add_time, o.after_sale_status, o.finish_time, rmr.headimgurl,  r.repair_name,  r.logo')
                ->join("mob_repair r", "o.repair_id = r.id", 'LEFT')
                ->join("mob_member_role_info rmr", "r.member_id = rmr.member_id and rmr.type = 1", 'LEFT')
                ->where("o.id",$param['order_id'])->find();

            $order_goods = db('order_product_server')->alias('op')->field('op.*, oa.status, oa.audit_type')
                ->join('mob_order_austin oa', 'oa.product_id = op.id AND oa.order_id = op.order_id', 'LEFT')
                ->where('op.order_id', $param['order_id'])->select();

            $data = [
                'order' => $order,
                'order_goods' => $order_goods
            ];
            return ['data'=>$data, 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取服务订单列表接口
    static public function order_server_list($param) {
        if ( !isset($param['member_id']) || !isset($param['status']))
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];

        try{
            $where = [];
            if ($param['status'] > 0) {
                if ($param['status'] == 99) {   // 99为获取待评价订单
                    $where['os.status'] = 6;
                    $where['os.is_comment'] = 0;
                } else if ($param['status'] == 98) {   // 98为获取已评价订单
                    $where['os.status'] = 6;
                    $where['os.is_comment'] = 1;
                } else {
                    $where['os.status'] = $param['status'];
                }
            }
            $where['os.member_id'] = $param['member_id'];
            $where['os.after_sale_status'] = 0;
            $order_list = Db::table('mob_order_server')->alias('os')
                ->field('os.id, os.province, os.order_price, os.city, os.area, os.street, os.msg, os.order_sn, os.add_time, os.order_receiving_time, os.status, os.after_sale_status, os.address, os.is_comment, si.item_name, r.logo, r.repair_name, oa.id as oa_id')
                ->join('mob_server_items si', 'si.id = os.type', 'LEFT')
                ->join("mob_repair r", "os.repair_id = r.id", 'LEFT')
                ->join("mob_order_austin oa", "oa.order_id = os.id AND oa.type = 2", 'LEFT')
                ->where($where)->order('os.id desc')->paginate();
            return ['data'=>$order_list->toArray(), 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }


    // 获取服务订单列表接口(维修店)
    static public function repair_order_server_list($param) {
        if ( !isset($param['member_id']) || !isset($param['status']))
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];

        $repair_id = Db::table('mob_repair')->where('member_id',$param['member_id'])->value('id');
        if(!$repair_id){
            return ['data' => '找不到维修店ID', 'code' => 400001, 'msg' => 'FAULT'];
        }

//        try{
            $where = [];
            if ($param['status'] > 0) {
                if ($param['status'] == 99) {   // 99为获取待评价订单
                    $where['os.status'] = 6;
                    $where['os.is_comment'] = 0;
                } else if ($param['status'] == 98) {   // 98为获取已评价订单
                    $where['os.status'] = 6;
                    $where['os.is_comment'] = 1;
                } else if ($param['status'] == 100) {   // 100为今日订单
//                    $toDayBegin = strtotime(date("Y-m-d") . " 0:0:0");
//                    $toDayEnd = strtotime(date("Y-m-d") . " 23:59:60");
//                    $where['os.order_receiving_time'] = array('egt',$toDayBegin);
//                    $where['os.order_receiving_time'] = array('elt',$toDayEnd);
                } else {
                    $where['os.status'] = $param['status'];
                }
            }
            $where['os.repair_id'] = $repair_id;
            if ($param['status'] == 100) {// 100为今日订单
                $order_list = Db::table('mob_order_server')->alias('os')->field('os.*, si.item_name, mr.headimgurl as logo, mr.nickname as repair_name, oa.id as oa_id')
                    ->join('mob_server_items si', 'si.id = os.type', 'LEFT')
                    ->join("mob_member_role_info mr", "os.member_id = mr.member_id and mr.type=0", 'LEFT')
                    ->join("mob_order_austin oa", "oa.order_id = os.id AND oa.type = 2", 'LEFT')
                    ->where($where)->whereTime('os.order_receiving_time','d')->order('os.add_time desc')->paginate();
            }else{
                $order_list = Db::table('mob_order_server')->alias('os')->field('os.*, si.item_name, mr.headimgurl as logo, mr.nickname as repair_name, oa.id as oa_id')
                    ->join('mob_server_items si', 'si.id = os.type', 'LEFT')
                    ->join("mob_member_role_info mr", "os.member_id = mr.member_id and mr.type=0", 'LEFT')
                    ->join("mob_order_austin oa", "oa.order_id = os.id AND oa.type = 2", 'LEFT')
                    ->where($where)->order('os.add_time desc')->paginate();
            }
            return ['data'=>$order_list->toArray(), 'code'=>200, 'msg'=> 'SUCCESS'];
//        } catch (\Exception $e) {
//            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
//        }
    }

    // 获取订单详情接口
    static public function order_server_info($param) {
        if (!isset($param['order_id']))
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];

        try{
            $order = db('order_server')->alias('o')
                ->field('o.status, o.service_time, o.add_time, o.msg, o.address, o.service_mode, o.id, o.order_price, o.lat, o.lon, o.img1, o.img2, o.img3, o.img4, o.img5, si.item_name,rmr.headimgurl r_headimgurl, mmr.headimgurl m_headimgurl, r.repair_name, r.lat r_lat, r.lon r_lon, r.phone r_phone, oa.id as oa_id, car.name as car_name')
                ->join('mob_server_items si', 'si.id = o.type', 'LEFT')
                ->join("mob_repair r", "o.repair_id = r.id", 'LEFT')
                ->join("mob_member_role_info rmr", "r.member_id = rmr.member_id and rmr.type = 1", 'LEFT')
                ->join("mob_member_role_info mmr", "o.member_id = mmr.member_id and mmr.type = 0", 'LEFT')
                ->join("mob_order_austin oa", "oa.order_id = o.id AND oa.type = 2", 'LEFT')
                ->join("mob_my_car car", "car.member_id = o.member_id", 'LEFT')
                ->where("o.id",$param['order_id'])->order("car.is_default desc")->find();

            return ['data'=>['order' => $order], 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'data'=>$param , 'msg'=> $e->getMessage()];
        }
    }

    // 删除订单接口
    static public function delete_order($param) {
        if ( !isset($param['member_id']) || !isset($param['order_id']) || !isset($param['model']))
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];

        try{
//            db('')
            return ['code'=>200,'msg'=>'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 订单申请售后接口
    static public function order_austin($param) {
        if ( !isset($param['member_id']) || !isset($param['order_id']) || !isset($param['product_id'])
            || !isset($param['cause']) || !isset($param['return_money'])
            || !isset($param['type']) || !isset($param['audit_type']) || !isset($param['obj_id']))
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];

        // 启动事务
        Db::startTrans();
        try{
            $return_money = $param['return_money'];
            if(!isset($param['order_austin_id']) || !$param['order_austin_id']) { // 没有ID的时候检查
                // 检查该产品是否已申请过售后
                $rs = Db::table('mob_order_austin')
                    ->where('order_id', $param['order_id'])
                    ->where('status', 'neq', 3)
                    ->where('product_id', $param['product_id'])
                    ->find();
                if ($rs) {
                    throw new \Exception('该产品已申请售后，请勿重复提交');
                }
            }
            $austin_sn = '104' . date('YmdHis') . rand(10000, 99999);
            $data = [
                'austin_sn' => $austin_sn,
                'order_id' => $param['order_id'],
                'product_id' => $param['product_id'],
                'obj_id' => $param['obj_id'],
                'type' => $param['type'],
                'audit_type' => $param['audit_type'],
                'cause' => $param['cause'],
                'return_money' => $param['return_money'],
                'add_time' => time(),
                'img1' => $param['img1'],
                'img2' => $param['img2'],
                'img3' => $param['img3'],
            ];
            if (isset($param['msg'])) {
                $data['msg'] = $param['msg'];
            }

            $models = ['', 'order_buy', 'order_server'];
            $model = $models[$param['type']];


            if(isset($param['order_austin_id']) && $param['order_austin_id'] > 0) { // 有传ID表示更新
                $order_austin_id = $param['order_austin_id'];
                Db::table('mob_order_austin')->where('id', $param['order_austin_id'])->where('member_id', $param['member_id'])->update($data);
            } else {
                $data['member_id'] = $param['member_id']; // 添加记录  追加用户ID
                $order_austin_id = Db::table('mob_order_austin')->insertGetId($data);

                // 将订单售后状态修改为1
                Db::table('mob_' . $model)->where('id', $param['order_id'])->update(['after_sale_status' => 1]);

                $models = ['', 'order_product_buy', 'order_product_server'];
                $model_p = $models[$param['type']];
                // 更新订单产品的售后状态
                Db::table('mob_' . $model_p)->where('id', $param['product_id'])->update(['austin_status' => $param['audit_type']]);
            }

            //订单业务
            if ($model == 'order_server') {
                // 获取订单维修店信息
                $merchant = Db::table('mob_repair')->alias('r')
                    ->field('r.id, r.member_id, m.phone, m.openid')
                    ->join('mob_member m', 'r.member_id = m.id')
                    ->where('r.id', $param['obj_id'])
                    ->find();
            } else {
                // 店铺商城功能尚未完成
                $merchant = [];
            }
            //dump($merchant);
            /*********
             *    用户提交服务单  提醒商家
             *
             ***/
            $url = 'http://' . $_SERVER['HTTP_HOST'] . '/wechat/r_austin/austin_info.html?id=' . $order_austin_id;

            $param = [
                'member_id' => $merchant['member_id'],
                'member_role' => 'repair',
                'msg_id' => 51,
            ];
            $params = [
                $austin_sn, $return_money, date('Y-m-d H:i:s'), 'url' => $url
            ];
            Message::creation_order_msg($param, $params);

            // 发送短信
//            $param = [ 'phone' => $merchant['phone'], 'type' => 33, 'model' => 3063083, 'params' => $merchant['order_sn'] ];
//            Common::send_note($param);
            // 发送微信模板消息

//            $data = [
//                'touser' => $merchant['openid'],
//                'template_id' => 'rnJUnlEzUqYEEwmXLKm-U2LpMW90D-7l71DqIzp4tkY',
//                'url' => $url,
//                'topcolor' => '#FF0000',
//                'data' => [
//                    'first' => [
//                        'value' => '订单付款',
//                        "color" => "#173177"
//                    ],
//                    'keyword1' => [
//                        'value' => $merchant['order_sn'],
//                        "color" => "#173177"
//                    ],
//                    'keyword2' => [
//                        'value' => $merchant['order_price'],
//                        "color" => "#173177"
//                    ],
//                    'keyword3' => [
//                        'value' => date('Y-m-d H:i:s'),
//                        "color" => "#173177"
//                    ],
//                    'keyword4' => [
//                        'value' => '订单已付款，请尽快完成订单内容',
//                        "color" => "#173177"
//                    ]
//                ]
//            ];
//            send_msg($data);

            Db::commit();
            return ['code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 订单售后状态更改接口
    static public function order_austin_status($param) {
        if(!isset($param['austin_id']) || !isset($param['member_id']) || !isset($param['status']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        $order_austin = Db::table('mob_order_austin')->where('id', $param['austin_id'])->where('member_id', $param['member_id'])->find();
        if(!$order_austin) {
            self::$err_code = 400056;
            throw new \Exception('FAULT');
        }

        $update['status'] = $param['status'];
        if(isset($param['merchant_msg'])) {
            $update['merchant_msg'] = $param['merchant_msg'];
        }

        // 修改订单状态
        // 启动事务
        Db::startTrans();
        try{
            Db::table('mob_order_austin')->where('id', $param['austin_id'])->where('member_id', $param['member_id'])->update($update);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

        //状态修改完成  根据状态处理业务逻辑
        switch ($param['status']) {
            case 1:  
                break;
            default:
                break;
        }
        return ['code'=>200, 'msg'=> 'SUCCESS'];
    }

    // 获取售后单列表
    static public function order_austin_list($param) {
        if(!isset($param['member_id']) || !isset($param['type']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $order_list = Db::table('mob_order_austin')->alias('oa')
                ->field('oa.*, r.logo, r.repair_name, o.order_price, op.product_image, op.product_name')
                ->join('mob_order_product_server op', 'op.id = oa.product_id')
                ->join('mob_order_server o', 'o.id = oa.order_id')
                ->join('mob_repair r', 'r.id = o.repair_id')
                ->where('oa.member_id', $param['member_id'])->where('oa.type', $param['type'])->where('oa.status', 'in', '0, 1, 2, 3')->paginate();
            return ['data'=>$order_list->toArray(), 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 获取投诉单列表
    static public function order_complaint_list($param) {
        if(!isset($param['member_id']) || !isset($param['type']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $order_list = Db::table('mob_order_austin')->alias('oa')
                ->field('oa.*, r.logo, r.repair_name, o.order_price, o.order_sn, op.product_image, op.product_name')
                ->join('mob_order_product_server op', 'op.id = oa.product_id')
                ->join('mob_order_server o', 'o.id = oa.order_id')
                ->join('mob_repair r', 'r.id = o.repair_id')
                ->where('oa.member_id', $param['member_id'])->where('oa.type', $param['type'])->where('oa.status', 'in', '4， 5')->paginate();
            return ['data'=>$order_list->toArray(), 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 余额支付
    static public function balance_paid($param) {
        if(!isset($param['member_id']) || !isset($param['order_id']) || !isset($param['model']) || !isset($param['coupon_id']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        $order_id = $param["order_id"];
        $coupon_id = $param["coupon_id"];
        $model = $param["model"];
        if($model != 'order_buy' && $model != 'order_server' && $model != 'order_server_deal') return ['data'=>'','code'=>400061,'msg'=> 'FAULT']; // 订单模型错误

        // 启动事务
        Db::startTrans();
        try{
            // 订单信息
            if($model == 'order_server_deal') {
                $order = Db::table('mob_' . $model)->alias('o')->field('o.member_id_to, o.order_sn, o.order_price, m.parent_id')
                    ->join('mob_member m', 'm.id = o.member_id_to')
                    ->where('o.id', (int)$order_id)->find();
            }else{
                $order = Db::table('mob_' . $model)->alias('o')->field('o.member_id, o.order_sn, o.order_price, m.parent_id')->join('mob_member m', 'm.id = o.member_id')->where('o.id', (int)$order_id)->find();
            }
            // 优惠券信息
            if ($coupon_id > 0) {
                $coupon = Db::table('mob_member_coupon')->alias('mc')->field('c.*')
                    ->join('mob_coupon c', 'c.id = mc.coupon_id')
                    ->where('mc.member_id', $param['member_id'])
                    ->where('mc.status', 0)
                    ->where('c.end_use_time', '> time', time())
                    ->where('c.start_use_time', '<= time', time())
                    ->where('mc.id', $coupon_id)->find();
                if ($coupon) {
                    $order['order_price'] -= $coupon['money'];
                }
                // 修改优惠券状态
                Db::table('mob_member_coupon')->where('id', $coupon_id)->update(['status' => 1]);

                $order_data['coupon_id'] = $coupon_id; // 优惠券ID
                $order_data['coupon_money'] = $coupon['money']; // 优惠金额
            }

            // 修改订单状态
            //订单业务
            if ($model == 'order_server' || $model == 'order_server_deal') {
                $order_data['status'] = 3; // 已付款状态
            } else {
                $order_data['status'] = 2; // 已付款状态
            }
            $order_data['order_price_payment'] = $order['order_price']; // 订单实付款
            $order_data['pay_time'] = time();  // 支付时间
            $order_data['pay_type'] = '余额'; // 支付类型

            Db::table('mob_' . $model)->where('id', $order_id)->update($order_data);

            if($model == 'order_server_deal') {
                // 修改维修店余额
                $money = Db::table('mob_repair')->where('member_id', $param['member_id'] )->value('money');
                if ($money < $order['order_price']) {
                    self::$err_code = 400040;
                    throw new \Exception('FAULT');
                }
                Db::table('mob_repair')->where('member_id', $param['member_id'])->setDec('money', $order['order_price']);

            }else{
                // 修改用户余额
                $money = Db::table('mob_member')->where('id', $param['member_id'])->value('money');
                if ($money < $order['order_price']) {
                    self::$err_code = 400040;
                    throw new \Exception('FAULT');
                }
                Db::table('mob_member')->where('id', $param['member_id'])->setDec('money', $order['order_price']);
            }

            // 添加账单记录
            if($model == 'order_server_deal'){
                $member_money = [
                    'member_id' => $order['member_id_to'], // 用户ID
                    'money' => $order['order_price'],  // 账单金额
                    'frozen_status' => 0, // 冻结状态，， 此处冻结，等订单彻底完成时，自动将冻结金额转为可用余额
                    'type' => 1, // 用户账户类型  0、普通账户  1、维修店账户  2、供应商账户  3、合伙人账户
                    'msg' => '维修店销售订单余额支付', // 账单说明
                    'source' => 9, // 资金来源 0、出账； 1、业务进账； 2、普通账户转入； 3、维修店转入； 4、经销商转入； 5、合伙人转入;  6 提现； 7 分销； 8充值; 9支付
                    'add_time' => time(), // 账单生成时间，
                    'order_sn' => $order['order_sn'], // 订单号
                    'order_model' => $model, // 订单模型
                    'pay_type' => '余额支付' // 交易方式
                ];
            }else{
                $member_money = [
                    'member_id' => $order['member_id'], // 用户ID
                    'money' => $order['order_price'],  // 账单金额
                    'frozen_status' => 0, // 冻结状态，， 此处冻结，等订单彻底完成时，自动将冻结金额转为可用余额
                    'type' => 0, // 用户账户类型  0、普通账户  1、维修店账户  2、供应商账户  3、合伙人账户
                    'msg' => '余额支付', // 账单说明
                    'source' => 9, // 资金来源 0、出账； 1、业务进账； 2、普通账户转入； 3、维修店转入； 4、经销商转入； 5、合伙人转入;  6 提现； 7 分销； 8充值; 9支付
                    'add_time' => time(), // 账单生成时间，
                    'order_sn' => $order['order_sn'], // 订单号
                    'order_model' => $model, // 订单模型
                    'pay_type' => '余额支付' // 交易方式
                ];

            }
            Db::table('mob_member_money')->insert($member_money); // 增加账单

            //订单业务
            if ($model == 'order_server' || $model == 'order_server_deal') {
                // 获取订单维修店信息
                $merchant = Db::table('mob_'.$model)->alias('o')
                    ->field('o.id order_id, o.order_sn, o.order_price, r.id, r.member_id, m.phone, m.openid')
                    ->join('mob_repair r', 'r.id = o.repair_id')
                    ->join('mob_member m', 'r.member_id = m.id')
                    ->where('o.order_sn', $order['order_sn'])
                    ->find();

                // 服务订单  给维修店增加待结算金额 增加账单
                $member_money = [
                    'member_id' => $merchant['member_id'], // 用户ID
                    'money' => $order['order_price'],  // 账单金额
                    'frozen_status' => 1, // 冻结金额
                    'type' => 1, // 用户账户类型  0、普通账户  1、维修店账户  2、供应商账户  3、合伙人账户
                    'msg' => '余额支付订单', // 账单说明
                    'source' => 1, // 资金来源 0、出账； 1、业务进账； 2、普通账户转入； 3、维修店转入； 4、经销商转入； 5、合伙人转入;  6 提现； 7 分销； 8充值; 9支付
                    'add_time' => time(), // 账单生成时间，
                    'order_sn' => $order['order_sn'], // 订单号
                    'order_model' => $model, // 订单模型
                    'pay_type' => '余额支付' // 交易方式
                ];
                Db::table('mob_member_money')->insert($member_money); // 增加账单
                Db::table('mob_repair')->where('id', $merchant['id'])->setInc('money_frozen', $order['order_price']); // 给维修店增加待结算金额

            } else {
                // 店铺商城功能尚未完成
                $merchant = [];
            }


            /*********
             *    订单支付成功  提醒商家
             *
             ***/
            $params[] = $merchant['order_sn'];
            $param = [ 'phone' => $merchant['phone'], 'type' => 33, 'model' => 3063083, 'params' => json_encode($params) ];
            Common::send_note($param);
            // 发送微信模板消息

            if($model == 'order_server_deal') {
                $url = 'http://' . $_SERVER['HTTP_HOST'] . '/wechat/r_orders/server_deal_goods.html?order_id=' . $merchant['order_id'];
            }else{
                $url = 'http://' . $_SERVER['HTTP_HOST'] . '/wechat/r_member/order_info.html?id=' . $merchant['order_id'];
            }
            if (isset($merchant['openid']) && $merchant['openid']) {
                $data = [
                    'touser' => $merchant['openid'],
                    'template_id' => 'bnzQgDYgRRSaNUhN0PxIkCDzZiAaKMyX_ijEt3bjOG4',
                    'url' => $url,
                    'topcolor' => '#FF0000',
                    'data' => [
                        'first' => [
                            'value' => '订单付款',
                            "color" => "#173177"
                        ],
                        'keyword1' => [
                            'value' => $merchant['order_sn'],
                            "color" => "#173177"
                        ],
                        'keyword2' => [
                            'value' => $merchant['order_price'],
                            "color" => "#173177"
                        ],
                        'keyword3' => [
                            'value' => date('Y-m-d H:i:s'),
                            "color" => "#173177"
                        ],
                        'keyword4' => [
                            'value' => '订单已付款，请尽快完成订单内容',
                            "color" => "#173177"
                        ]
                    ]
                ];
                send_msg($data);
            }
            // 推送站内信息
            $param = [
                'member_id' => $merchant['member_id'],
                'member_role' => 'repair',
                'msg_id' => 38,
            ];
            $params = [
                $merchant['order_sn'], $merchant['order_price'], date('Y-m-d H:i:s'), 'url' => $url
            ];
            Message::creation_order_msg($param, $params);
            // 提交事务
            Db::commit();
            return ['code' => 200, 'msg' => 'success', 'data' => ['order_price' => $order['order_price']]];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }


    // 获取订单列表接口
    static public function repair_order_list($param) {
        if ( !isset($param['repair_id']) || !isset($param['status']) || !isset($param['model']))
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        $model = $param['model'];
        if($model != 'order_buy' && $model != 'order_server') return ['data'=>'','code'=>400061,'msg'=> 'FAULT']; // 订单模型错误

        try{
            $where = [];
            if ($param['status'] > 0) {
                $where['os.status'] = $param['status'];
            }
            $where['os.repair_id'] = $param['repair_id'];
            //return ['data'=>$param, 'code'=>0, 'msg'=> 'FAULT'];
            $order_list = Db::table('mob_'.$model)->alias('os')->field('os.*, si.item_name, mr.headimgurl')
                ->join('mob_server_items si', 'si.id = os.type', 'LEFT')
                ->join("mob_member_role_info mr", "os.member_id = mr.member_id and mr.type = 0", 'LEFT')
                ->where($where)->paginate();
            return ['data'=>$order_list, 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }


    // 重新推送订单接口
    static public function push_again($param) {
        if ( !isset($param['id']) || !isset($param['model']) || !isset($param['member_id']) || !isset($param['msg']))
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];
        Db::startTrans();
        try {
            $id = $param['id'];
            $model = $param['model'];
            $member_id = $param['member_id'];

            $order = Db::table('mob_' . $model)->where('id', $id)->where('member_id', $member_id)->find();
            if (time() - $order['push_time'] < 480) {
                self::$err_code = 400118;
                throw new \Exception('请勿频繁推送，两次间隔至少8分钟！');
            }
            $update_data = [
                'repair_id' => 0,  //维修店ID
                'status' => 1, //订单状态
                'order_receiving_time' => 0, //接单时间
                'remind_status' => 0, //超时提醒状态
                'push_time' => time(), //更新推送时间
            ];
            Db::table('mob_' . $model)->where('id', $id)->where('member_id', $member_id)->update($update_data);

            // 添加重新推送记录
            $push_again_data = [
                'order_id' => $id,
                'add_time' => time(),
                'member_id' => $member_id,
                'repair_id' => $order['repair_id'],
                'msg' => $param['msg']
            ];
            Db::table('mob_order_push_again_log')->insert($push_again_data);

            // 根据下单用户经纬度 获取维修店列表
            $coord = getAround($order['lat'], $order['lon'], 3000);
            $where = 'lat > ' . $coord[0] . ' AND lat < ' . $coord[1] . ' AND lon > ' . $coord[2] . ' AND lon < ' . $coord[3] . ' AND audit_status = 4';
            $repair_list = Db::table('mob_repair')->alias('r')->field('r.*, m.phone as m_phone, m.openid')
                ->join('mob_member m', 'r.member_id = m.id')
                ->where($where)->select();
            foreach ($repair_list as $r) {

                /*--- 新订单消息推送 */
                $params = [
                    'order_id' => $id,
                    'member_id' => $r['member_id'],
                    'order_sn' => $order['order_sn'],
                    'm_phone' => $r['m_phone'],
                    'openid' => $r['openid'],
                ];
                new_order_push_msg($params); 
                // 新订单消息推送 -- end
            }
            // 提交事务
            Db::commit();
            return ['code' => 200, 'msg' => 'success'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }


    //===============================销售采购==============================


    // 获取服务订单列表接口(维修店)
    static public function repair_order_server_list_deal($param) {
        if ( !isset($param['member_id']) || !isset($param['status']))
            return ['data' => '', 'code' => 400001, 'msg' => 'FAULT'];

        $repair_id = Db::table('mob_repair')->where('member_id',$param['member_id'])->value('id');
        if(!$repair_id){
            return ['data' => '找不到维修店ID', 'code' => 400001, 'msg' => 'FAULT'];
        }

        try{

            if ($param['status']==0) {
                $field1 = "os.repair_id_to";
                $field2 = "os.repair_id";
            }else{
                $field1 = "os.repair_id";
                $field2 = "os.repair_id_to";
            }

            $order_list = Db::table('mob_order_server_deal')->alias('os')->field('os.id,os.add_time,os.order_price,os.status,os.order_receiving_time,os.after_sale_status,os.is_comment, mr.logo, mr.repair_name,ops.product_name,ops.product_num,ops.product_price')
                ->join("mob_repair mr", "mr.id = ".$field1." ", 'LEFT')
                ->join('mob_order_product_server_deal ops', 'os.id = ops.order_id', 'LEFT')
                ->where($field2,$repair_id)->order('os.id desc')->paginate();
            $order_list = $order_list->toArray();
            $tmpI = $tmpNum = $tmpUn = 0;
            for($i=0;$i<count($order_list["data"]);$i++){
                if($tmpNum!=$order_list["data"][$i]["id"]){
                    $tmpNum = $order_list["data"][$i]["id"];
                    $tmpI = $i;
                    $tmpUn = 0;
                }else{
                    $tmpUn = 1;
                }
                if($order_list["data"][$i]["product_name"]){
                    $order_list["data"][$tmpI]["product"][] = [
                        $order_list["data"][$i]["product_name"],$order_list["data"][$i]["product_num"],$order_list["data"][$i]["product_price"]
                    ];
                }else{
                    $order_list["data"][$tmpI]["product"] = [];
                }
                if($tmpUn){unset($order_list["data"][$i]);}
                unset($order_list["data"][$i]["product_name"]);
                unset($order_list["data"][$i]["product_num"]);
                unset($order_list["data"][$i]["product_price"]);
            }
            //print_r($order_list);exit();

            return ['data'=>$order_list, 'code'=>200, 'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }


    // 销售采购订单支付接口
    static public function deal_pay($param) {
        if(!isset($param['order_id']) || !isset($param['member_id']) || !isset($param['model']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        if($param['model'] != 'order_server_deal') return ['data'=>'','code'=>400061,'msg'=> 'FAULT']; // 订单模型错误

        try{
            $model = $param['model'];
//            if ($model == 'order_server') {
                $join = [ ['mob_repair r','r.id = o.repair_id', 'LEFT'] ];
                $field = 'o.*, r.repair_name as company_name, r.cover';
//            } else {
//                $join = [ ['mob_shop s','r.s = o.shop_id', 'LEFT'] ];
//                $field = 'o.*, s.shop_name as company_name, s.cover';
//            }
            $order = Db::table('mob_'.$model)->alias('o')->field($field)->join($join)
                ->where('o.id', $param['order_id'])
                ->where('o.member_id_to', $param['member_id'])
                ->find();
            if ( $order['status'] != 2 ) {
                self::$err_code = 400057;
                throw new \Exception('FAULT');
            }
            return ['data'=>$order,'code'=>200,'msg'=> 'SUCCESS']; // 返回支付订单数据
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }


}
